package com.hyfd.service.mp;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.util.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.hyfd.common.BaseJson;
import com.hyfd.common.Page;
import com.hyfd.dao.mp.checkBalanceDao;
import com.hyfd.service.BaseService;

import net.sf.jxls.transformer.XLSTransformer;

@Service
public class checkBalanceSer extends BaseService{

	@Autowired
	checkBalanceDao cbDao;
	
	public void checkBalance(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> param = getMaps(request);
		String startDate = param.get("startDate")+"";
		String endDate = param.get("endDate")+"";
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		//获取当前时间段跑量的代理商ID
		List<String> agentIdList = cbDao.selectAgentId(param);
		for(String agentId : agentIdList){
			Map<String,Object> balanceMap = new HashMap<String,Object>();
			balanceMap.put("agentId", agentId);
			balanceMap.put("date", startDate);
			double startBalance = cbDao.selectAgentBalance(balanceMap);
			balanceMap.put("date", endDate);
			double endBalance = cbDao.selectAgentBalance(balanceMap);
			param.put("agentId", agentId);
			double addmoney = cbDao.selectAgentAddMoney(param);
			double adjustment = cbDao.selectAdjustment(param);
			Map<String,Object> consumeMap = cbDao.selectConsume(param);
			double consume = Double.parseDouble(consumeMap.get("consume")+"");
			double actualDeductions = cbDao.selectActualDeductions(param);
			double agentDiff = cbDao.selectAgentDiff(param);
			consumeMap.put("agentdiff", agentDiff);
			consumeMap.put("diff", String.format("%.2f",(consume + actualDeductions - agentDiff)));
			consumeMap.put("actualDeductions", actualDeductions);
			consumeMap.put("startbalance", startBalance);
			consumeMap.put("endbalance", endBalance);
			consumeMap.put("addmoney", addmoney);
			consumeMap.put("adjustment", adjustment);
			list.add(consumeMap);
		}
		List<Map<String,Object>> mdList = cbDao.selectMultipleDeductions(param);
		double sumMd = 0.0;
		for(Map<String,Object> md : mdList){
			sumMd += Double.parseDouble(md.get("fee")+"");
			String orderId = md.get("order_id")+"";
			String agentId = md.get("agent_id")+"";
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("orderId", orderId);
			map.put("agentId", agentId);
			double sumFee = cbDao.selectChargeFee(map);
			if(sumFee==0.0){
				md.put("result", "是");
			}else{
				md.put("result", "否");
			}
		}
		List<Map<String,Object>> diffList = cbDao.selectDiff(param);
		double sumDiff = 0.0;
		for(Map<String,Object> diff : diffList){
			sumDiff += Double.parseDouble(diff.get("diff")+"");
		}
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("title", startDate+"——"+endDate);
		map.put("time", DateUtil.formatDate(new Date(), "yyyy.MM.dd"));
		map.put("list", list);
		map.put("mdList", mdList);
		map.put("diffList", diffList);
		map.put("sumMd", sumMd);
		map.put("sumDiff", String.format("%.2f", sumDiff));
		exportExcel("balanceTemp","checkBalance"+System.currentTimeMillis(),map,request,response);
	}
	
	/**
	 * 导出excel文件
	 * @author lks 2017年7月5日上午10:21:46
	 * @param tempName
	 * @param fileName
	 * @param map
	 * @param request
	 * @param response
	 */
	public static void exportExcel(String tempName,String fileName,Map<String,Object> map,HttpServletRequest request,HttpServletResponse response){
		String templatePath = request.getServletContext().getRealPath("/") + File.separator + "downloadFiles"+ File.separator +tempName+".xlsx";
        XLSTransformer former = new XLSTransformer();
        try
        {
            response.setContentType("application/x-excel;charset=utf-8");
            response.setHeader("Content-Disposition",
                "attachment;filename=" + fileName + ".xlsx");
            response.setCharacterEncoding("utf-8");
            FileInputStream in = new FileInputStream(templatePath);
            XSSFWorkbook workbook = (XSSFWorkbook)(former.transformXLS(in, map));
            OutputStream os = response.getOutputStream();
            workbook.write(os);
            os.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
	}
	
	public String checkBalanceList(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> param = getMaps(request);
		String startDate = param.get("startDate")+"";
		String endDate = param.get("endDate")+"";
		//Map<String,Object> user = getUser();
		StringBuilder sb=new StringBuilder();
		try{
			Page p=getPage(param);//提取分页参数
			List<String> agentIdList = cbDao.selectAgentId(param);
			int total = cbDao.selectAgentIdCount(param);
			p.setCount(total);
			int pageNum=p.getCurrentPage();
			int pageSize=p.getPageSize();
			
			sb.append("{");
			sb.append(""+getKey("page")+":"+p.getCurrentPage()+",");
			sb.append(""+getKey("total")+":"+p.getNumCount()+",");
			sb.append(""+getKey("records")+":"+p.getCount()+",");
			sb.append(""+getKey("rows")+":"+"");
			
			PageHelper.startPage(pageNum, pageSize);//mybatis分页插件
			List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
			//获取当前时间段跑量的代理商ID
			for(String agentId : agentIdList){
				Map<String,Object> balanceMap = new HashMap<String,Object>();
				balanceMap.put("agentId", agentId);
				balanceMap.put("date", startDate);
				double startBalance = cbDao.selectAgentBalance(balanceMap);
				balanceMap.put("date", endDate);
				double endBalance = cbDao.selectAgentBalance(balanceMap);
				param.put("agentId", agentId);
				double addmoney = cbDao.selectAgentAddMoney(param);
				double adjustment = cbDao.selectAdjustment(param);
				Map<String,Object> consumeMap = cbDao.selectConsume(param);
				double consume = Double.parseDouble(consumeMap.get("consume")+"");
				double actualDeductions = cbDao.selectActualDeductions(param);
				double agentDiff = cbDao.selectAgentDiff(param);
				consumeMap.put("agentdiff", agentDiff);
				consumeMap.put("diff", String.format("%.2f",(consume + actualDeductions - agentDiff)));
				consumeMap.put("actualDeductions", actualDeductions);
				consumeMap.put("startbalance", startBalance);
				consumeMap.put("endbalance", endBalance);
				consumeMap.put("addmoney", addmoney);
				consumeMap.put("adjustment", adjustment);
				list.add(consumeMap);
			}
			String dataListJson=BaseJson.listToJson(list);
			sb.append(dataListJson);
			sb.append("}");
		}catch(Exception e){
			log.error("订单提交记录列表查询方法出错"+e.getMessage());
		}
		
		return sb.toString();
	}
	
}
